package hn.cch.grammar.java;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 遍历删除
 */


public class RemoveDemo {

    List<String> stringList = new ArrayList<String>();

    @BeforeEach
    public void before() {

        stringList.add("hello");
        stringList.add("world");
        stringList.add("hello");
        stringList.add("world");

        stringList.add("hello");
        stringList.add("hello");
        stringList.add("world");
        stringList.add("world");

        System.out.println("list size 0 " + stringList.size());
        System.out.println(stringList);
    }

    /**
     * 使用forIndex删除结果错误
     */
    @Test
    public void forIndex() {

        for (int i = 0; i < stringList.size(); i++) {
            String string = stringList.get(i);
            System.out.println("string 0 " + string);
            if (string.equals("hello")) {
                stringList.remove(string);
            }
        }
        System.out.println("list size 1 " + stringList.size());
        System.out.println(stringList);
    }

    /**
     * 使用foreach删除抛出异常
     */
    @Test
    public void foreach() {
        System.out.println("list size 1 " + stringList.size());

        for (String string : stringList) {
            System.out.println("string 0 " + string);
            if (string.equals("hello")) {
                stringList.remove(string);
            }
        }
        System.out.println("list size 2 " + stringList.size());
        System.out.println(stringList);
    }


    /**
     * 使用iterator删除结果正常
     */
    @Test
    public void iterator() {

        Iterator<String> stringIterator = stringList.iterator();
        while (stringIterator.hasNext()) {
            String string = stringIterator.next();
            System.out.println("string 0 " + string);
            if (string.equals("hello")) {
                // stringList.remove(string);//使用List错
                stringIterator.remove();// 使用Iterator正确
            }
        }
        System.out.println("list size 3 " + stringList.size());
        System.out.println(stringList);
    }
}
